package com.example.testcalendaractivity;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.widget.CalendarView;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.testcalendaractivity.db.Event;
import com.example.testcalendaractivity.util.ChineseWeekDayFormatter;
import com.example.testcalendaractivity.util.EventDecorator;
import com.example.testcalendaractivity.util.MonthPicker;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnDateSelectedListener;
import com.prolificinteractive.materialcalendarview.OnMonthChangedListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;


public class TestCalendarActivity extends AppCompatActivity implements View.OnClickListener {
    private Button btnAddEvent, btnSelectMonthYear, btnToday, left, right;
    private MaterialCalendarView calendarView2;
    Calendar eventSaveDate = Calendar.getInstance();
    Calendar selectedDate = Calendar.getInstance();
    private MonthPicker monthPicker;

    private final ActivityResultLauncher<Intent> mLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
        if (result.getResultCode() == RESULT_OK && result.getData() != null) {
            eventSaveDate.setTimeInMillis(result.getData().getLongExtra("selectedDate",eventSaveDate.getTimeInMillis()));
            selectedDate = eventSaveDate;
        }
    });

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
            finish();
        }
        super.onCreate(savedInstanceState);
//        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_test_calendar);



        btnAddEvent = findViewById(R.id.btn_add_event);
        calendarView2 = findViewById(R.id.calendarView2);
        btnSelectMonthYear = findViewById(R.id.btnSelectMonthYear);
        btnToday = findViewById(R.id.btnGoToToday);
        left = findViewById(R.id.btn_left);
        right = findViewById(R.id.btn_right);
        //日历初始为今天
        Calendar today = Calendar.getInstance();
        calendarView2.setCurrentDate(today);
        calendarView2.setSelectedDate(today);
        //权限查询
//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_CALENDAR ,Manifest.permission.READ_CALENDAR}, 1);
//        }


        loadEventsForDate(today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH));


        // 隐藏日历顶部的年月和箭头
        calendarView2.post(() -> {
            View titleView = calendarView2.getChildAt(0);
            if (titleView != null) {
                titleView.setVisibility(View.GONE);
            }
        });

        calendarView2.setWeekDayFormatter(new ChineseWeekDayFormatter());




        // 首次进入时加载当前月份的事件
        loadEventsForCurrentMonth();

        // 日历点击事件
        calendarView2.setOnDateChangedListener(new OnDateSelectedListener() {
            @Override
            public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay date, boolean selected) {
                int year = date.getYear();
                int month = date.getMonth();
                int day = date.getDay();
                selectedDate.set(year,month,day);
                loadEventsForDate(year, month, day);
//                calendarView2.addDecorator(new TodayColorDecorator(TestCalendarActivity.this));
            }
        });


        // 设置翻页监听器，每次翻页时加载当前页的事件
        calendarView2.setOnMonthChangedListener(new OnMonthChangedListener() {
            @Override
            public void onMonthChanged(MaterialCalendarView widget, CalendarDay date) {
                loadEventsForCurrentMonth();
            }
        });

        // 设置添加事件按钮点击
        btnAddEvent.setOnClickListener(this);
        // 年月选择监听
        btnSelectMonthYear.setOnClickListener(this);
        // 返回今日监听
        btnToday.setOnClickListener(this);
        //日期左右切换
        left.setOnClickListener(this);
        right.setOnClickListener(this);


    }




    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btnGoToToday) {
            Calendar today = Calendar.getInstance();
            calendarView2.setCurrentDate(CalendarDay.today());
            calendarView2.setSelectedDate(CalendarDay.today());
            selectedDate = today;
            loadEventsForDate(today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH));
        } else if (v.getId() == R.id.btnSelectMonthYear) {
            showMonthYearPicker();
        } else if (v.getId() == R.id.btn_left) {
            calendarView2.goToPrevious();
        } else if (v.getId() == R.id.btn_right) {
            calendarView2.goToNext();
        } else if (v.getId() == R.id.btn_add_event) {
            Intent intent = new Intent(TestCalendarActivity.this, AddEventActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt("year", calendarView2.getSelectedDate().getYear());
            bundle.putInt("month", calendarView2.getSelectedDate().getMonth());
            bundle.putInt("day", calendarView2.getSelectedDate().getDay());
            intent.putExtras(bundle);
            // 启动添加事件的界面
            mLauncher.launch(intent);
        }
    }

    @Override
    protected void onResume() {
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
            finish();
        }
        super.onResume();
        //每次进入页面重置状态
        resetToDefaultState();
        loadEventsForCurrentMonth();

    }


    // 显示年月选择框
    @SuppressLint("ResourceType")
    private void showMonthYearPicker() {

//        DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {
//            @Override
//            public void onDateSet(DatePicker datePicker, int year, int month, int day) {
//                btnSelectMonthYear.setText(String.format("%d年%02d月", year, month + 1));
//                CalendarDay selectedDate = CalendarDay.from(year, month, day);
//                calendarView2.setCurrentDate(selectedDate);
//            }
//        };
//        new DatePickerDialog(TestCalendarActivity.this, 3, onDateSetListener, calendarView2.getCurrentDate().getYear(), calendarView2.getCurrentDate().getMonth(), calendarView2.getCurrentDate().getDay()).show();

        // 创建对话框
        Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.month_picker_dialog);

        // 获取 MonthPicker 控件
        monthPicker = dialog.findViewById(R.id.monthPicker);

        // 设置确认按钮点击事件
        Button btnConfirm = dialog.findViewById(R.id.btnConfirm);
        btnConfirm.setOnClickListener(v -> {
            int year = monthPicker.getYear();
            int month = monthPicker.getMonth();
            // 在这里处理用户选择的年月
            // 例如：Toast显示
            Toast.makeText(this, "选择的日期: " + year + "-" + (month + 1), Toast.LENGTH_SHORT).show();
            dialog.dismiss();
            btnSelectMonthYear.setText(String.format("%d年%02d月", year, month + 1));
            CalendarDay selectedMonth = CalendarDay.from(year, month, selectedDate.get(Calendar.DAY_OF_MONTH));
            calendarView2.setCurrentDate(selectedMonth);
        });
        dialog.show();



    }




    //获取并显示所选日期的事件
    @SuppressLint("Range")
    private void loadEventsForDate(int year, int month, int day) {

        Calendar beginTime = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"));  // Calendar类处理日期和时间.这里注意时区！
        beginTime.set(year, month, day, 0, 0, 0);
        long startMillis = beginTime.getTimeInMillis(); //获取19701月1日至今的毫秒数

        Calendar endTime = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"));
        endTime.set(year, month, day, 23, 59, 59);
        long endMillis = endTime.getTimeInMillis();

        // 构建 Instances URI，设置查询范围
        Uri.Builder builder = CalendarContract.Instances.CONTENT_URI.buildUpon();
        ContentUris.appendId(builder, startMillis);
        ContentUris.appendId(builder, endMillis);

        // 查询字段，包括 ORIGINAL_ID
        String[] projection = new String[]{
                CalendarContract.Instances.EVENT_ID,
                CalendarContract.Instances.ORIGINAL_ID,
                CalendarContract.Instances.BEGIN,
                CalendarContract.Instances.END,
                CalendarContract.Instances.TITLE,
                CalendarContract.Instances.DESCRIPTION,
                CalendarContract.Instances.EVENT_LOCATION,
                CalendarContract.Instances.RRULE
        };

        // 筛选条件
        String selection = "(" + CalendarContract.Instances.BEGIN + " >= ?) AND (" + CalendarContract.Instances.BEGIN + " <= ?) AND (" + CalendarContract.Instances.OWNER_ACCOUNT + " = ?)";
        String[] selectionArgs = new String[]{String.valueOf(startMillis - 1000), String.valueOf(endMillis), "ADBC_calendar"};
        String sortOrder = "begin ASC";
        ContentResolver cr = getContentResolver(); // 访问其他应用的数据——包括联系人、日历、媒体库等
        Cursor cursor = cr.query(builder.build(), projection, selection, selectionArgs, sortOrder);
        if (cursor != null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            List<Event> events = new ArrayList<>();
            while (cursor.moveToNext()) {
                long eventId = cursor.getLong(cursor.getColumnIndex(CalendarContract.Instances.EVENT_ID));
                long startDate = cursor.getLong(cursor.getColumnIndex(CalendarContract.Instances.BEGIN));
                long endDate = cursor.getLong(cursor.getColumnIndex(CalendarContract.Instances.END));
                String description = cursor.getString(cursor.getColumnIndex(CalendarContract.Instances.DESCRIPTION));
                String location = cursor.getString(cursor.getColumnIndex(CalendarContract.Instances.EVENT_LOCATION));
                String rrule = cursor.getString(cursor.getColumnIndex(CalendarContract.Instances.RRULE));
                String title = cursor.getString(cursor.getColumnIndex(CalendarContract.Instances.TITLE));
//                // 格式化时间
//                String formattedBeginTime = dateFormat.format(new Date(startDate));
//                String formattedEndTime = dateFormat.format(new Date(endDate));
                events.add(new Event(eventId, title, startDate, endDate, description, location, rrule));
            }
            cursor.close();
            //传递事件数据到Fragment
            showEventsInFragment(events);
        }
    }


    private void showEventsInFragment(List<Event> events) {
        LinearLayout fragmentContainer = findViewById(R.id.fragmentContainer);
        // 移除旧的fragment
        fragmentContainer.removeAllViews();

        for (Event event : events) {
            EventFragment fragment = EventFragment.newInstance(
                    event.getTitle(),
                    event.getStartDate(),
                    event.getEndDate(),
                    event.getDescription(),
                    event.getLocation(),
                    event.getEventID()
            );
            // 使用 LayoutInflater 动态加载碎片视图 调用fragment.onCreateView 使碎片创建自己的界面
            View fragmentView = fragment.onCreateView(getLayoutInflater(), fragmentContainer, null);
            // 将碎片视图添加到LinearLayout容器中
            fragmentContainer.addView(fragmentView);

            fragmentView.setOnClickListener(v -> {
                // 当点击碎片时，触发事件
                openEventEditActivity(event.getEventID(), event.getTitle(), event.getStartDate(), event.getEndDate(), event.getDescription(), event.getLocation(), event.getRule());
            });
        }
    }

    void openEventEditActivity(long eventId, String title, long startDate, long endDate, String description, String location, String rule) {
        Intent intent = new Intent(TestCalendarActivity.this, EditEventActivity.class);
        intent.putExtra("eventId", eventId);
        intent.putExtra("eventTitle", title);
        intent.putExtra("eventStartDate", startDate);
        intent.putExtra("eventEndDate", endDate);
        intent.putExtra("eventDescription", description);
        intent.putExtra("eventLocation", location);
        intent.putExtra("rrule", rule);

        mLauncher.launch(intent);
    }

    @SuppressLint("SetTextI18n")
    private void loadEventsForCurrentMonth() {
        // 获取当前月份的第一天和最后一天
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"));
        Calendar beginTime = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"));  // Calendar类处理日期和时间.这里注意时区！
        beginTime.set(calendarView2.getCurrentDate().getYear(), calendarView2.getCurrentDate().getMonth(), 1, 0, 0, 0);
        long startMillis = beginTime.getTimeInMillis(); //获取19701月1日至今的毫秒数
        int showMonth = calendarView2.getCurrentDate().getMonth() + 1;
        btnSelectMonthYear.setText(calendarView2.getCurrentDate().getYear() + "年" + showMonth + "月");

        int lastDay = beginTime.getActualMaximum(Calendar.DAY_OF_MONTH);
        Calendar endTime = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"));
        endTime.set(calendarView2.getCurrentDate().getYear(), calendarView2.getCurrentDate().getMonth(), lastDay, 23, 59, 59);
        long endMillis = endTime.getTimeInMillis();

        List<CalendarDay> eventDates = new ArrayList<>();

        // 构建 Instances URI，设置查询范围
        Uri.Builder builder = CalendarContract.Instances.CONTENT_URI.buildUpon();
        ContentUris.appendId(builder, startMillis);
        ContentUris.appendId(builder, endMillis);

        // 筛选条件
        String selection = "(" + CalendarContract.Instances.BEGIN + " >= ?) AND (" + CalendarContract.Instances.BEGIN + " <= ?) AND (" + CalendarContract.Instances.OWNER_ACCOUNT + " = ?)";
        String[] selectionArgs = new String[]{String.valueOf(startMillis - 1000), String.valueOf(endMillis), "ADBC_calendar"};
        ContentResolver cr = getContentResolver(); // 访问其他应用的数据——包括联系人、日历、媒体库等
        // 查询事件的 URI
        Cursor cursor = cr.query(
                builder.build(),
                new String[]{CalendarContract.Instances.BEGIN}, // 查询的列
                selection, // 筛选条件
                selectionArgs, // 筛选参数
                null // 排序
        );

        if (cursor != null) {
            while (cursor.moveToNext()) {
                @SuppressLint("Range")
                long startEventMillis = cursor.getLong(cursor.getColumnIndex(CalendarContract.Instances.BEGIN));
                calendar.setTimeInMillis(startEventMillis);
                // 将事件的日期转换为 CalendarDay
                CalendarDay eventDate = CalendarDay.from(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                eventDates.add(eventDate);
            }
            cursor.close();
        } else {
            Toast.makeText(this, "无法获取系统日历事件", Toast.LENGTH_SHORT).show();
        }

        // 清除之前的装饰器，重新添加当前月份的事件
        calendarView2.removeDecorators();
        if (!eventDates.isEmpty()) {
            calendarView2.addDecorator(new EventDecorator(Color.RED, new HashSet<>(eventDates)));
        }
    }

    // 将 CalendarDay 转换为时间戳（毫秒）
    private long calendarDayToMillis(CalendarDay day) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(day.getYear(), day.getMonth() - 1, day.getDay());
        return calendar.getTimeInMillis();
    }

    private void resetToDefaultState() {

        // 清空显示的事件
        LinearLayout fragmentContainer = findViewById(R.id.fragmentContainer);
        fragmentContainer.removeAllViews();
        // 将 CalendarView 重置为当前日期
        MaterialCalendarView calendarView1 = findViewById(R.id.calendarView2);
        calendarView1.clearSelection();  // 这将取消所有选中的日期
        calendarView1.setDateSelected(selectedDate, true);
        calendarView1.setCurrentDate(selectedDate);
        loadEventsForDate(selectedDate.get(Calendar.YEAR), selectedDate.get(Calendar.MONTH), selectedDate.get(Calendar.DAY_OF_MONTH));
    }
}